package org.demo.nio.reactor.multiplethread;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by tangwy on 2017/10/30.
 */
public class RWHandler implements Runnable {
    private Selector selector;
    private SocketChannel channel;
    private SelectionKey sk;
    public RWHandler(Selector selector, SocketChannel channel) throws IOException {
        if(selector==null){
            throw new NullPointerException("selector is null");
        }
        if(channel==null){
            throw new NullPointerException("channel is null");
        }
        this.selector = selector;
        this.channel = channel;
        this.channel.configureBlocking(false);
        sk=channel.register(selector, SelectionKey.OP_READ,this);
    }

    @Override
    public void run() {
        if(!sk.isValid()){
            return;
        }
        if(sk.isReadable()){
            System.out.println("read");
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            try {
                channel.read(buffer);
                buffer.flip();
                byte[]bytes=new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println(new String(bytes));
                channel.register(selector, SelectionKey.OP_WRITE, this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(sk.isWritable()){
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            buffer.put("Server\r\n".getBytes());
            buffer.flip();
            try {
                channel.write(buffer);
                channel.register(selector, SelectionKey.OP_READ, this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
